/*
' Copyright (c) 2014 Diadrasis
'  All rights reserved.
' 
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
' DEALINGS IN THE SOFTWARE.
' 
*/

using System;
using DotNetNuke.Services.Exceptions;
using net.diadrasis.dnn.jsImageGallery.Components;
using DotNetNuke.Common;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Services.FileSystem;

namespace net.diadrasis.dnn.jsImageGallery
{

    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The EditjsImageGallery class is used to manage content
    /// 
    /// Typically your edit control would be used to create new content, or edit existing content within your module.
    /// The ControlKey for this control is "Edit", and is defined in the manifest (.dnn) file.
    /// 
    /// Because the control inherits from jsImageGalleryModuleBase you have access to any custom properties
    /// defined there, as well as properties from DNN such as PortalId, ModuleId, TabId, UserId and many more.
    /// 
    /// </summary>
    /// -----------------------------------------------------------------------------
    public partial class Edit : jsImageGalleryModuleBase
    {

        public int imgsecId;

        #region Event Handlers

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// -----------------------------------------------------------------------------
        private void Page_Load(object sender, System.EventArgs e)
        {
            try
            {                

                if (Page.IsPostBack == false){                    
                    //get image section
                    string imgsec = Request.QueryString["imgsecid"];
                    if (imgsec != null){
                        imgsecId = Convert.ToInt32(imgsec);
                    }
                    else{
                        imgsecId = -1;
                    }                  
                    
                    gvImages.DataSource = cImageController.GetSectionImages(imgsecId);
                    gvImages.DataBind();

                    //set column width
                    foreach (DataControlField column in gvImages.Columns){
                        if (column.HeaderText == "Title" || column.HeaderText == "URL"){
                            column.ItemStyle.Width = Unit.Pixel(200);
                        }
                    }

                    this.addBtn.Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(Globals.NavigateURL("AddImage", "mid=" + this.ModuleId.ToString() + "&imgsecid=" + imgsecId), this, PortalSettings, true, false));
                    this.imgSec.Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(Globals.NavigateURL("Edit", "mid=" + this.ModuleId.ToString()), this, PortalSettings, true, false));
                    for (int i = 0; i < gvImages.Rows.Count; i++){
                        string iid = FindImagePath(gvImages.DataKeys[i]["file"].ToString());
                        gvImages.Rows[i].Cells[getColumnID("edit image")].Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(Globals.NavigateURL("AddImage", "mid=" + this.ModuleId.ToString() + "&imgid=" + gvImages.DataKeys[i]["id"] + "&imgsecid=" + gvImages.DataKeys[i]["imgsecID"]), this, PortalSettings, true, false));
                        int test =(int)gvImages.DataKeys[i].Value;
                    }
                }
               


            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        #endregion

        //to avoid refering to cell index
        protected int getColumnID(string columnName) {
            int columnID = 0;
            foreach (DataControlField column in gvImages.Columns)
            {
                if (column.HeaderText == columnName)
                {
                    columnID = gvImages.Columns.IndexOf(column);
                    break;
                }
            }
            return columnID;
        }
      
      

        protected void gvImages_RowCommand(Object sender, GridViewCommandEventArgs e)
        {
            
                if (e.CommandName == "Delete")
                {
                    string message = e.CommandArgument.ToString();
                    cImageController.DeleteImage(Convert.ToInt32(message));
                    Response.Redirect(UrlUtils.PopUpUrl(Globals.NavigateURL(EditUrl()), this, PortalSettings, false, false)); 
                }
                else
                {
                    Response.Redirect(DotNetNuke.Common.Globals.NavigateURL());
                }
            

        }
       
        protected string FindImagePath(string dnnImgID)
        {
            int id=Convert.ToInt32(dnnImgID.Substring(7));
            FileInfo imgInfo = (FileInfo)FileManager.Instance.GetFile(id);
            string url =PortalSettings.HomeDirectory + imgInfo.Folder + imgInfo.FileName;
            return url;
        }
    }
}